package com.wangwei.basic;


import edu.princeton.cs.algs4.StdOut;

/**
 * 数组实现的环形队列
 *
 * @param <Item>
 */
public class RingQueue<Item> {

    private Item[] arr;
    private int begin;
    private int end;
    private int maxSize;


    public RingQueue(int maxSize){
        arr=(Item[]) new Object[maxSize];
        this.maxSize =maxSize;
    }


    public void enqueue(Item item) throws Exception {
        if(isFull()) {
            throw new Exception("队列已满");
        }
        arr[end]= item;
        end =(end+1) % maxSize;
    }

    public Item dequeue() throws Exception {
        if(isEmpty()){
            throw new Exception("队列已空");
        }
        Item temp = arr[begin];
        begin=(begin+1)%maxSize;
        return temp;
    }

    public void show(){
//      for(int i = begin;i<size();i++){
        for(int i = begin;i<begin+size();i++){
            System.out.printf("arr[%d]=%s\t",i%maxSize,arr[i%maxSize].toString());
        }
    }

    public boolean isEmpty(){
        return begin == end;
    }


    public boolean isFull(){
        return (end + 1 ) % maxSize == begin;
    }

    public int size(){
        return (end + maxSize - begin) % maxSize;
    }


    public static void test(String exp){
        RingQueue<String> s =new RingQueue<>(4);
        String[] arr =exp.split(" ");
        for(String item : arr){
            if(!item.equals("-")){
                try {
                    s.enqueue(item);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }else if(!s.isEmpty()){
                try {
                    StdOut.println("弹出："+s.dequeue()+"");
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            s.show();
            System.out.println();
        }
        StdOut.println("("+s.size()+" left on queue)");
    }

    public static void main(String[] args) {
        String exp="to be or not to - be - - that - - - is";
        test(exp);
    }



}